package com.ukit.weather_xml.Other.DataManger.Cityes

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.ukit.weather_xml.Other.DataManger.UserCity
import com.ukit.weather_xml.R

class CityAdapter(
    private val cities: List<UserCity>,
    private val onCityClickListener: OnCityClickListener
) :
    RecyclerView.Adapter<CityAdapter.CityViewHolder>() {

    private val diffUtilCallback: DiffUtil.ItemCallback<UserCity> = object : DiffUtil.ItemCallback<UserCity>() {
        override fun areItemsTheSame(oldItem: UserCity, newItem: UserCity): Boolean = oldItem.id == newItem.id

        override fun areContentsTheSame(oldItem: UserCity, newItem: UserCity): Boolean = oldItem == newItem
    }

    private val asyncListDiffer = AsyncListDiffer(this, diffUtilCallback)

    fun clearData() {
        asyncListDiffer.submitList(emptyList())
    }
    fun setData(cities: List<UserCity>) {
        asyncListDiffer.submitList(cities)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CityViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.city_item, parent, false)
        return CityViewHolder(view)
    }

    override fun onBindViewHolder(holder: CityViewHolder, position: Int) {
        val city = asyncListDiffer.currentList[position]
        holder.bind(city)
        holder.cityNameButton.setOnClickListener {
            onCityClickListener.onCityClick(city)
        }
    }

    override fun getItemCount(): Int = asyncListDiffer.currentList.size

    inner class CityViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val cityNameButton: Button = itemView.findViewById(R.id.change)

        fun bind(city: UserCity) {
            cityNameButton.text = city.city
        }
    }

    interface OnCityClickListener {
        fun onCityClick(city: UserCity)
    }
}
